package com.weibo4j.api;


import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.weibo4j.api.json.JSON;

public abstract class WeiboResponse<T> {
	
	private final static Logger LOGGER  = LoggerFactory.getLogger(WeiboResponse.class);

    protected JSONObject          result;

    protected boolean             success = true;
 
    private String              errorMessage;

    private String              errorCode;

    protected String              jsonString;
    
    public boolean isSuccess() {
        if (success) {
            success = !result.containsKey("error") && !result.containsKey("error_code");
            if (!success) {
                errorCode = result.getString("error_code");
                errorMessage = result.getString("error");
            }
        }
        return success;
    }

    public String getErrorMessage() {
		return errorMessage;
	}

	public String getErrorCode() {
		return errorCode;
	}
    
	public void setHttpResponse(HttpResponse resp) {
        HttpEntity entity = resp.getEntity();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            jsonString = br.readLine();
            br.close();
            result = JSON.parse(jsonString);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            success = false;
            errorMessage = e.getMessage();
        }
    }
	
	protected abstract T getModel();
}
